// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '../views/LoginView.vue'
import HomeView from '../views/HomeView.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: LoginView,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: 'Home',
    component: HomeView,
    meta: { requiresAuth: true } // 需要登录才能访问
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫：处理登录权限
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token') // 或从 Pinia 获取

  if (to.meta.requiresAuth && !token) {
    // 需要登录但未登录 → 跳转登录页
    next({ name: 'Login' })
  } else if (to.name === 'Login' && token) {
    // 已登录还访问登录页 → 跳首页
    next({ name: 'Home' })
  } else {
    next()
  }
})

export default router